<template>
  <view class="index-container">
    <!-- 自定义导航栏 -->
    <custom-nav title="汉·瑜伽普拉提" :show-back="false">
      <!-- 自定义右侧内容 -->
      <template #right>
        <view @click="handleShare">
          <uni-icons type="share" size="22"></uni-icons>
        </view>
      </template>
    </custom-nav>
    <!-- 顶部内容 -->
    <view class="top-section" :style="{ paddingTop: navHeight + 'px' }">
      <view class="search-box" @click="goSearch">
        <view class="input">搜索你想要的信息</view>
        <!-- <input type="text" placeholder="搜索你想要的信息" placeholder-class="placeholder" /> -->
        <text class="iconfont icon-search"></text>
      </view>

      <!-- 主banner -->
      <Bannar v-if="bannerList.length > 0" :list="bannerList" />

      <!-- 功能导航 -->
      <view class="nav-grid">
        <view class="nav-item" v-for="(item, index) in navList" :key="index" @tap="navTo(item.url)">
          <view class="nav-logo">
            <image :src="commonStore.baseImageUrl + 'test-yujia/' + item.icon" mode="widthFix" width="50rpx" />
          </view>
          <text>{{ item.name }}</text>
        </view>
      </view>
    </view>

    <view style="background: linear-gradient(to bottom, #edede3 70%, #fdfefa)">
      <!-- 门店展示 -->
      <view class="store-content">
        <view class="title-box">
          <text class="title">门店展示</text>
          <view class="change-store" @click="showStorePicker = true">
            <text>更换门店</text>
            <image class="switch-icon" :src="commonStore.baseImageUrl + 'test-yujia/index/switch-icon.png'
              " mode="widthFix" width="12rpx" height="19rpx"></image>
          </view>
        </view>
        <view class="store-card" v-if="storeDetail && storeDetail.branchCode" @click="goToStoreDetail">
          <image :src="storeDetail?.photo" mode="aspectFill"></image>
          <view class="store-info">
            <image class="store-logo" :src="commonStore.baseImageUrl + 'test-yujia/index/store-logo.png'
              " mode="widthFix" />
            <view>
              <view class="store-name">{{ storeDetail?.name }}</view>
              <view class="store-address">门店地址：{{ storeDetail?.address }}</view>
            </view>
            <image class="icon-phone" :src="commonStore.baseImageUrl + 'test-yujia/index/call-icon.png'"
              @click.stop="callHandle" />
          </view>
        </view>
        <u-picker :show="showStorePicker" keyName="name" :columns="[commonStore.storeList]" @confirm="handleStoreChange"
          @close="showStorePicker = false" @cancel="showStorePicker = false"></u-picker>
      </view>

      <!-- 会员福利 -->
      <view style="padding: 20rpx" @click="goToVipBenefits">
        <vipBenefits />
      </view>

      <!-- 推荐课程 -->
      <recommendedCourses :list="recommendCourses" />
      <view style="height: 16rpx; background: #d8dfbb"></view>

      <!-- 教练团队 -->
      <trainerTeam :teacherList="teacherList" />

      <!-- 排行榜 -->
      <rankingList v-if="commonStore.storeAndCityInfo.branchCode" />

      <!-- 互动 -->
      <view class="activity-section">
        <view class="invite-item" @click="waiterShare">
          <text class="title">邀请好友</text>
          <text class="desc">免费领取课程</text>
          <view class="invite-btn">
            <text>点击分享</text>
            <image class="icon" :src="commonStore.baseImageUrl + 'test-yujia/index/worming-icon.png'" mode="widthFix">
            </image>
          </view>
          <image class="invite-icon" :src="commonStore.baseImageUrl + 'test-yujia/index/index-invite.png'"
            mode="widthFix">
          </image>
        </view>

        <view class="jiameng-item invite-item" @click="waiterShare">
          <text class="title">加盟汉·瑜伽</text>
          <text class="desc">免费领取课程</text>
          <view class="invite-btn">
            <text>点击了解</text>
            <image class="icon" :src="commonStore.baseImageUrl + 'test-yujia/index/worming-icon.png'" mode="widthFix">
            </image>
          </view>
          <image class="jiameng-icon" :src="commonStore.baseImageUrl + 'test-yujia/index/index-jiameng.png'"
            mode="widthFix">
          </image>
        </view>
      </view>

      <!-- 底部内容 -->
      <footer-content />
    </view>

    <!-- 底部导航栏 -->
    <tab-bar />
  </view>
</template>

<script setup>
import { useCommonStore, useUserStore, useReservationStore } from "@/store";
import { ref, onMounted } from "vue";
import Bannar from "./components/bannar.vue";
import vipBenefits from "./components/vip-benefits.vue";
import RecommendedCourses from "./components/recommended-courses.vue";
import TrainerTeam from "./components/trainer-team.vue";
import RankingList from "./components/ranking-list.vue";
import TabBar from "@/components/TabBar.vue";
import { useNavHeight } from "@/utils/useNavHeight";
import {
  getBannerListAPI,
  getStoreListAPI,
  getStoreDetailAPI,
  getRecommendCourseAPI,
  setCityAndStoreAPI,
  getTeacherListAPI,
} from "@/apis/home";
import { getCityListAPI, getStoreAndCityInfoAPI } from "@/apis/common";
import { onShow, onShareAppMessage, onLoad } from "@dcloudio/uni-app";

const commonStore = useCommonStore();
const reservationStore = useReservationStore();
const userStore = useUserStore();

const { navHeight } = useNavHeight();
const bannerList = ref([]);
const navList = ref([
  {
    name: "明星老师 ",
    icon: "index/mingxing-iocn.png",
    url: "/pages/reservation/reservation?type=privateCourse",
  },
  { name: "约课", icon: "index/yueke-icon.png", url: "/pages/reservation/reservation?type=group" },
  { name: "商城", icon: "index/shangcheng.png", url: "/pages/shop/shop" },
  {
    name: "精品课程",
    icon: "index/jingpingke-icon.png",
    url: "/pages/reservation/reservation",
  },
]);
const storeDetail = ref(null);
const recommendCourses = ref([]);
const showStorePicker = ref(false);
const teacherList = ref([]);


// 添加分享功能
onShareAppMessage(() => {
  return {
    title: '汉·瑜伽普拉提', // 分享标题
    path: '/pages/index/index', // 分享路径，默认当前页面路径
    imageUrl: storeDetail.value?.photo || '', // 分享图片，使用门店图片，如果没有则使用默认图片
  }
});

const waiterShare = () => {
  uni.navigateTo({ url: "/pages/subpackages/activity/invited-user" })
}

const navTo = (url) => {
  // 先存储要传递的参数
  if (url.includes('/pages/reservation/reservation')) {
    const type = url.split('type=')[1];
    reservationStore.setReservationType(type);
  }
  uni.switchTab({ url });
};

const goSearch = () => {
  uni.navigateTo({ url: "/pages/search/search" });
};

const goToVipBenefits = () => {
  commonStore.showCommonSoon()
};

const goToStoreDetail = () => {
  uni.navigateTo({ url: "/pages/subpackages/shopCenter/store-detail?branchCode=" + storeDetail.value.branchCode });
};

// 切换门店
const handleStoreChange = (picked) => {
  if (!picked.value[0]) {
    showStorePicker.value = false;
    return;
  }
  const store = picked.value[0];
  const currentStore = {
    branchName: store.name,
    branchCode: store.branchCode,
    cityName: store.cityName,
    cityCode: store.city,
  };
  _setCity(currentStore);
  commonStore.setStoreAndCityInfo({ ...currentStore });
  getStoreDetail({ objectCode: currentStore.branchCode });
  getRecommendCourse({ branchCode: currentStore.branchCode });
  getTeacherList({ branchCode: currentStore.branchCode });
  showStorePicker.value = false;
};

const getBannerList = () => {
  getBannerListAPI().then((res) => {
    console.log("res", res);
    if (res.code === "200") {
      bannerList.value = res.data;
    }
  });
};

const getCityList = async () => {
  const { code, data } = await getCityListAPI();
  if (code === "200") {
    commonStore.setCityList(data);
  }
};

const getStoreList = async (params) => {
  const { code, data } = await getStoreListAPI(params);
  if (code === "200") {
    commonStore.setStoreList(data);
    console.log("storeList", commonStore.storeList);
  }
};

const getStoreDetail = async (params) => {
  const { code, data } = await getStoreDetailAPI(params);
  if (code === "200") {
    storeDetail.value = data;
    console.log("storeDetail", storeDetail.value);
  }
};

const getRecommendCourse = async (params) => {
  const { code, data } = await getRecommendCourseAPI(params);
  if (code === "200") {
    console.log("recommendCourse", data);
    recommendCourses.value = data;
  }
};

const getTeacherList = async (params) => {
  const { data, code } = await getTeacherListAPI(params);
  if (code === "200") {
    teacherList.value = data;
  }
};

const callHandle = () => {
  uni.makePhoneCall({
    phoneNumber: storeDetail.value.contactPhone,
  });
};

// 设置城市
const _setCity = async (city) => {
  const { code, data } = await setCityAndStoreAPI(
    city 
  );
  // 重新获取首页信息
  if (code === "200") {
    // commonStore.setStoreAndCityInfo(data)
    // getStoreDetail({objectCode: commonStore.storeAndCityInfo.branchCode})
    // getRecommendCourse({branchCode:commonStore.storeAndCityInfo.branchCode})
  }
};

// 默认门店和城市初始信息
const getStoreAndCityInfo = async () => {
  // await _setCity();
  const { code, data } = await getStoreAndCityInfoAPI();
  if (code === "200") {
    commonStore.setStoreAndCityInfo(data);
    console.log("storeAndCityInfo", commonStore.storeAndCityInfo);
    getStoreList({
      cityCode:  commonStore.storeAndCityInfo.cityCode,
    }); 
    getStoreDetail({ objectCode: commonStore.storeAndCityInfo.branchCode });
    getRecommendCourse({ branchCode: commonStore.storeAndCityInfo.branchCode });
    getTeacherList({ branchCode: commonStore.storeAndCityInfo.branchCode });
  }
};

// onMounted(() => {
//   getStoreAndCityInfo();
//   getBannerList();
//   getCityList();
//   console.log(userStore.token);
//   if (!userStore.token) {
//     uni.navigateTo({ url: "/pages/login/index" });
//   }
// });

onLoad((options) => {
  console.log("onLoad options", options);
  // 处理邀请码
  if (options.invitedCode) {
    console.log("invitedCode", options.invitedCode);
   
  }
})

onShow(() => {
  getStoreAndCityInfo();
  getBannerList();
  getCityList();

})
</script>

<style lang="scss">
.index-container {
  min-height: 100vh;
  width: 100%;
  max-width: 100%;
  padding: 0;
  margin: 0;
  padding-bottom: calc(60rpx + var(--safe-area-inset-bottom));
  overflow: hidden;

  .top-section {
    width: 100%;
    display: flex;
    flex-direction: column;
    background: linear-gradient(to bottom, #8cb22c 20%, #edede3);
    padding: 30rpx;
    box-sizing: border-box;
    margin: 0;
  }

  .search-box {
    margin-bottom: 30rpx;
    margin-top: 30rpx;

    .input {
      text-align: center;
      background: #fff;
      height: 56rpx;
      line-height: 56rpx;
      border-radius: 25rpx;
      // padding: 0 80rpx;
      font-size: 28rpx;
      box-sizing: border-box;
      box-shadow: 0rpx 3rpx 5rpx 0rpx rgba(199, 199, 199, 0.82);
    }

    .placeholder {
      color: #b4b4b4;
    }

    .icon-search {
      position: absolute;
      left: 30rpx;
      top: 50%;
      transform: translateY(-50%);
      color: #999;
    }
  }

  .nav-grid {
    display: flex;
    justify-content: space-between;
    margin-bottom: 40rpx;

    .nav-item {
      display: flex;
      flex-direction: column;
      align-items: center;

      .nav-logo {
        width: 90rpx;
        height: 88rpx;
        display: flex;
        align-items: center;
        justify-content: center;

        image {
          width: 100%;
          height: 100%;
        }
      }

      text {
        font-size: 24rpx;
        color: #333;
      }
    }
  }

  .store-content {
    padding: 0 30rpx;
    box-sizing: border-box;

    .title-box {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 24rpx;
      color: #000;
      margin-bottom: 20rpx;

      .title {
        display: flex;
        align-items: center;

        &::before {
          content: " ";
          width: 4rpx;
          height: 26rpx;
          background: #a4b870;
          border-radius: 50%;
          border-radius: 2rpx;
          margin-right: 12rpx;
        }
      }

      .change-store {
        display: flex;
        align-items: center;

        .switch-icon {
          width: 12rpx;
          height: 19rpx;
          margin-left: 10rpx;
        }
      }
    }

    .store-card {
      position: relative;
      border-radius: 20rpx;
      overflow: hidden;
      background: #eee;
      margin-top: 26rpx;
      height: 470rpx;

      image {
        width: 100%;
        height: 100%;
      }

      .store-info {
        position: absolute;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0, 0, 0, 0.5);
        height: 122rpx;
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 0 30rpx;

        .store-name {
          font-size: 32rpx;
          font-weight: bold;
          margin-bottom: 10rpx;
          color: #fff;
        }

        .store-logo {
          width: 80rpx;
          height: 90rpx;
        }

        .store-address {
          font-size: 24rpx;
          color: #fff;
        }

        .icon-phone {
          width: 24rpx;
          height: 25rpx;
        }
      }
    }
  }

  .activity-section {
    display: flex;
    justify-content: space-between;
    padding: 0 30rpx;
    box-sizing: border-box;
    gap: 50rpx;
    margin-top: 18rpx;


    .invite-item {
      color: #fff;
      display: flex;
      flex-direction: column;
      justify-content: center;
      background-color: #B0C56F;
      border-radius: 26rpx;
      position: relative;
      flex: 1;
      height: 190rpx;
      padding: 24rpx;
      box-sizing: border-box;

      .invite-icon {
        width: 160rpx;
        height: 146rpx;
        position: absolute;
        bottom: 0;
        right: -50rpx;
      }

      .jiameng-icon {
        width: 198rpx;
        height: 150rpx;
        position: absolute;
        bottom: 0;
        right: -50rpx;
      }

      .title {
        font-size: 32rpx;
      }

      .desc {
        font-size: 20rpx;
      }

      .invite-btn {
        font-size: 20rpx;
        background-color: #60702D;
        position: relative;
        border-radius: 20rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        width: 120rpx;
        margin-top: 16rpx;
        padding: 2rpx 10rpx;
        padding-left: 0;

        .icon {
          width: 23rpx;
          height: 31rpx;
          position: absolute;
          right: -4rpx;
          top: -4rpx;
        }
      }

    }
  }
}
</style>